package cn.ichiva.ftp;

import cn.hutool.extra.ftp.SimpleFtpServer;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.ftplet.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class FastFTPServer {
    private static final Logger log = LoggerFactory.getLogger(FastFTPServer.class);
    public static void main(String[] args) throws IOException {
        String root = "./";
        if(args.length != 0){
            root = args[0];
        }

        int[] ports = {21,11945,11946,11955,11946,11045,11145,12945,13945,14945};

        for (int port : ports) {
            try {
                launch(port,null,root);
                log.info("ftp server start.");
                log.info("ftp://127.0.0.1:{}", port);
                return;
            }catch (IOException e){
                throw e;
            }catch (FtpServerConfigurationException e){
                log.info("Address already in use:{}" , port);
            }
        }
        log.info("ftp server can not start.");
    }

    /**
     * 启动ftp服务器
     * @param port 端口
     * @param users 用户
     * @throws IOException
     */
    static void launch(int port, List<User> users,String... anonymous) throws IOException {
        SimpleFtpServer server = SimpleFtpServer.create();
        server.setPort(port);
        if(users != null && users.size() > 0){
            for (User user : users) {
                String homeDirectory = user.getHomeDirectory();
                createFile(homeDirectory);
                server.addUser(user);
            }
        }else {
            if(anonymous.length != 0){
                for (String anonymouFile : anonymous) {
                    File file = createFile(anonymouFile);
                    server.addAnonymous(file.getAbsolutePath());
                }
            }else {
                server.addAnonymous(createFile("./").getAbsolutePath());
            }
        }
        server.start();
    }

    static File createFile(String homeDirectory) throws IOException {
        File file = new File(homeDirectory);
        if(!file.exists()) file.createNewFile();
        System.out.println("root file: " + file.getAbsoluteFile());
        return file;
    }
}
